package file

import (
	"github.com/gin-gonic/gin"
	"log"
	"mime"
	"net/http"
	"one-wiki/commons"
	"one-wiki/config"
	"os"
	"path/filepath"
)

func FileHandlersInit(engine *gin.Engine) {
	group := engine.Group("/file")

	group.POST("/upload", upload)
	group.GET("/preview/:filename", preview)

}

func preview(context *gin.Context) {
	filename := context.Param("filename")

	// 获取文件路径和扩展名
	fpath := filepath.Join(config.FileUploadConfig.UploadPath, filename)
	ext := filepath.Ext(filename)

	// 检查文件是否存在
	if _, err := os.Stat(fpath); os.IsNotExist(err) {
		context.AbortWithStatus(http.StatusNotFound)
		return
	}

	// 读取文件内容
	data, err := os.ReadFile(fpath)
	if err != nil {
		context.AbortWithError(http.StatusInternalServerError, err)
		return
	}

	// 设置 MIME 类型和 Cache-Control 头
	mimeType := mime.TypeByExtension(ext)
	context.Header("Content-Type", mimeType)
	context.Header("Cache-Control", "public, max-age=86400") // 一天内缓存有效

	// 返回文件内容
	context.Data(http.StatusOK, mimeType, data)
}

func upload(context *gin.Context) {
	file, err := context.FormFile("file[]")
	if err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}
	log.Println(file.Filename)
	dst := config.FileUploadConfig.UploadPath + file.Filename
	err = context.SaveUploadedFile(file, dst)
	if err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	resp := commons.FileUploadResponse{
		Msg:  "上传成功",
		Code: 0,
		Data: commons.FileUploadResponseData{
			ErrFiles: []string{file.Filename},
			SuccMap: map[string]string{
				file.Filename: config.FileUploadConfig.PreviewPath + file.Filename,
			},
		},
	}
	context.JSON(http.StatusOK, resp)
}
